package cn.qyd.atomic;

import sun.misc.Unsafe;

import static cn.qyd.atomic.UnsafeDemo01.getUnsafe;

/**
 * @author 邱运铎
 * @date 2024-03-25 1:15
 */
public class UnsafeCompareAndSwapInt {
    private volatile int a;
    private static Unsafe unsafe;

    static {
        try {
            unsafe = getUnsafe();
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        UnsafeCompareAndSwapInt demo = new UnsafeCompareAndSwapInt();
        new Thread(() -> {
            for (int i = 1; i < 5; i++) {
                try {
                    demo.increment(i);
                    System.out.print(demo.a + " ");
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 5; i < 10; i++) {
                try {
                    demo.increment(i);
                    System.out.print(demo.a + " ");
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void increment(int x) throws NoSuchFieldException {
        while (true) {
            long fieldOffset = unsafe.objectFieldOffset(UnsafeCompareAndSwapInt.class.getDeclaredField("a"));
            if ( unsafe.compareAndSwapInt(this, fieldOffset, x - 1, x)) {
                break;
            }
        }
    }
}
